package com.enotary.flutter_obs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import io.flutter.plugin.common.EventChannel;

/**
 * 处理EventChannel逻辑
 */
public class ObsJavaEventChannel implements EventChannel.StreamHandler {

//    public EventChannel eventChannel;
    private EventChannel.EventSink events;
    private final List<OBSManager> obsManagers = new ArrayList<>();

    public static ObsJavaEventChannel getInstance() {
        return new ObsJavaEventChannel();
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        this.events = events;
    }

    @Override
    public void onCancel(Object arguments) {
        events = null;
        ObsUtils.logI("java event channel on cancel " + (arguments == null ? null : arguments.toString()));
    }


    /**
     * 该推送消息，要在主线程调用
     */
    public void eventSink(Object data) {
        if (events != null) events.success(data);
    }

    /**
     * 开始请求上传文件
     */
    public boolean startUpload(List<HashMap<String, Object>> list,String filePathCheckPoint, OBSManager.EventCallback callback) {
        if (list == null || list.size() <= 0) {
            return false;
        }
        ObsUtils.logI("obs manager checkEmptyRequest");
        checkEmptyRequest();
        for (HashMap<String, Object> item : list) {
            OBSManager manager = OBSManager.getInstance(item, filePathCheckPoint, data -> {
                if (callback != null) callback.callback(data);
                //if (events != null) events.success(data);
                //遍历  上传 过程中 移除 容易出现崩溃，截图文件上传很快 上传完 可能还没遍历完
                // java.util.ConcurrentModificationException at java.util.ArrayList$Itr.remove(ArrayList.java:875)
//                Object status = data == null ? null : data.get("status");
//                if (status instanceof Integer && (Integer) status != 1) {
//                    AppUtils.LogI("obs manager checkEmptyRequest by callback, status "+status);
//                    checkEmptyRequest();
//                }
            });
            obsManagers.add(manager);
        }
        return true;
    }


    /**
     * 将已经结束的对象 移除
     */
    public void checkEmptyRequest() {
        try {
            Iterator<OBSManager> i = obsManagers.iterator();
            while (i.hasNext()) {
                OBSManager item = i.next();
                if (item.isCancel()) {
                    ObsUtils.logI("obs manager remove " + item.getCancelKey());
                    i.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消存证
     *
     * @param cancelKey 上传的文件路径
     */
    public boolean cancelUpload(String cancelKey) {
        try {
            Iterator<OBSManager> i = obsManagers.iterator();
            ObsUtils.logI("cancelUpload size " + obsManagers.size() + ",key " + cancelKey);
            if (cancelKey != null) {
                while (i.hasNext()) {
                    OBSManager item = i.next();
                    if (cancelKey.equals(item.getCancelKey())) {
                        ObsUtils.logI("cancelUpload " + item.getCancelKey());
                        item.cancel();
                        i.remove();
                        return true;
                    }
                    //已经运行结束，则移除
                    if (item.isCancel()) {
                        i.remove();
                    }
                }
                return false;
            }
            //全部清空
            while (i.hasNext()) {
                i.next().cancel();
                i.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obsManagers.isEmpty();
    }
}
